import java.util.Arrays;

/**
 * @author VernHe
 * @date 2021年10月29日 11:52
 */
public class Solution_0581 {
    public int findUnsortedSubarray(int[] nums) {
        int result = 0;
        int len = nums.length;
        if (len < 2) {
            return result;
        }
        int[] sortedNums = Arrays.copyOf(nums, len);
        Arrays.sort(sortedNums);
        // 确定边界
        int leftIndex = 0;
        int rightIndex = nums.length - 1;
        // [1,2,3]  [1,2]
        while (leftIndex < len && nums[leftIndex] == sortedNums[leftIndex]) {
            leftIndex++;
        }
        // 说明是有序的
        if (leftIndex == len) {
            return result;
        }
        while (rightIndex >= 0 && nums[rightIndex] == sortedNums[rightIndex]) {
            rightIndex--;
        }
        return rightIndex - leftIndex + 1;
    }

    public static void main(String[] args) {
        System.out.println(new Solution_0581().findUnsortedSubarray(new int[]{2,6,4,8,10,9,15}));
        System.out.println(new Solution_0581().findUnsortedSubarray(new int[]{1,2,3,4}));
    }
}
